package Handlers

import (
	"backend/Service/SQL/MySQL"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Model_info struct {
	Status       bool     `json:"status"`
	Addr         string   `json:"addr"`
	Model_name   string   `json:"model_name"`
	Input_shape  []uint64 `json:"input_shape"`
	Output_shape []uint64 `json:"output_shape"`
}

type server_add_info struct {
	Addr string `json:"addr" xml:"addr" form:"addr" binding:"required"`
}

// 获取数据库中的模型服务列表
func Servers(c *gin.Context) {
	// 获取保存的服务器列表
	server_info, err := get_servers_info()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": err.Error()})
	}
	c.JSON(http.StatusOK, gin.H{"data": server_info})
}

func ServersAdd(c *gin.Context) {
	upload_data := server_add_info{}
	if err := c.ShouldBind(&upload_data); err != nil {
		c.JSON(http.StatusOK, gin.H{"err": err.Error()})
		return
	}
	data := &MySQL.Model_server{Addr: upload_data.Addr}
	// 试图查找该记录
	result := MySQL.DB_conn_for_udcpp.Where("addr = ?", data.Addr).Limit(1).Find(data)
	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{"err": result.Error.Error()})
		return
	}
	// 没有该记录
	if result.RowsAffected == 0 {
		result = MySQL.DB_conn_for_udcpp.Create(data)
		if result.Error != nil {
			c.JSON(http.StatusOK, gin.H{"err": result.Error.Error()})
			return
		}
	}
	// 获取新的状态
	server_info, err := get_servers_info()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": server_info})
}

func ServersDelete(c *gin.Context) {
	servers, err := get_servers_info()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": err.Error()})
		return
	}
	ans := make([]Model_info, 0)
	record := make(map[string]bool)
	for index := range *servers {
		if (*servers)[index].Status {
			// 可用则保留
			ans = append(ans, (*servers)[index])
		} else {
			pre_len := len(record)
			record[(*servers)[index].Addr] = false
			end_len := len(record)
			// 长度没变->处理过了
			if pre_len == end_len {
				continue
			}
			// 不可用则从数据库删除
			result := MySQL.DB_conn_for_udcpp.Where("addr = ?", (*servers)[index].Addr).Delete(&MySQL.Model_server{})
			if result.Error != nil {
				c.JSON(http.StatusOK, gin.H{"err": result.Error.Error()})
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{"data": ans})
}
